package cn.csc.module.order.controller.app;


import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.framework.common.pojo.PageResult;
import cn.csc.module.order.controller.admin.order.vo.OrderPageReqVO;
import cn.csc.module.order.controller.app.dto.OrderBaseReqDTO;
import cn.csc.module.order.controller.app.vo.OrderRespVO;
import cn.csc.module.order.convert.addr.OrderAddrConvert;
import cn.csc.module.order.convert.item.OrderItemConvert;
import cn.csc.module.order.convert.order.OrderConvert;
import cn.csc.module.order.dal.dataobject.addr.OrderAddrDO;
import cn.csc.module.order.dal.dataobject.item.OrderItemDO;
import cn.csc.module.order.dal.dataobject.order.OrderDO;
import cn.csc.module.order.enums.ErrorCodeConstants;
import cn.csc.module.order.enums.OrderStatusEnum;
import cn.csc.module.order.mq.producer.hzh.OrderReceiptForHzhProducer;
import cn.csc.module.order.service.addr.OrderAddrService;
import cn.csc.module.order.service.item.OrderItemService;
import cn.csc.module.order.service.order.OrderService;
import cn.csc.module.pay.api.order.PayOrderApi;
import cn.csc.module.pay.api.order.dto.CreateDivideReqDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static cn.csc.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csc.framework.common.pojo.CommonResult.error;
import static cn.csc.framework.common.pojo.CommonResult.success;
import static cn.csc.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 我的订单
 *
 * @author FrozenWatermelon
 */
@RestController
@RequestMapping("/order/my")
@Tag(name = "app-我的订单接口")
@Slf4j
public class MyOrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderAddrService orderAddrService;

    @Autowired
    private PayOrderApi payOrderApi;

    @Autowired
    private OrderReceiptForHzhProducer orderReceiptForHzhProducer;

    /**
     * 订单详情信息接口
     */
    @GetMapping("/order_detail")
    @Operation(summary = "订单详情信息" , description = "根据订单号获取订单详情信息")
    @Parameter(name = "orderId", description = "订单号" , required = true)
    public CommonResult<OrderRespVO> orderDetail(@RequestParam(value = "orderId") BigInteger orderId) {
        log.info("[MyOrderController][orderDetail][orderId]=={}",orderId);
        OrderDO orderDO = orderService.get(orderId);
        log.info("[MyOrderController][orderDetail][orderDO]=={}",orderDO);
        if(orderDO==null){
            return error(ErrorCodeConstants.ORDER_ITEM_NOT_EXISTS);
        }
        OrderRespVO orderRespVO = OrderConvert.INSTANCE.convertVo(orderDO);
        orderRespVO.setOrderId(orderDO.getId());

        //查询订单项
        List<OrderItemDO> items = orderItemService.getItemByOrderId(orderId);
        orderRespVO.setOrderItems(OrderItemConvert.INSTANCE.convertVoList(items));
        //查订单详细地址
        OrderAddrDO orderAddrDO = orderAddrService.getAddrByOrderId(orderId);
        orderRespVO.setOrderAddr(OrderAddrConvert.INSTANCE.convertVo(orderAddrDO).setOrderAddrId(orderAddrDO.getId()));
        return success(orderRespVO);
    }


    /**
     * 买家订单列表-分页获取
     */
    @GetMapping("/search_order")
    @Operation(summary = "订单列表信息查询" , description = "根据订单编号或者订单中商品名称搜索")
    public CommonResult<PageResult<OrderRespVO>> searchOrder(@Valid OrderPageReqVO pageVO) {
        pageVO.setUserId(BigInteger.valueOf(getLoginUserId()));
        pageVO.setOrderStatus(4);//查全部
        PageResult<OrderRespVO> pageResult = orderService.getMiniPage(pageVO);
        return success(pageResult);
    }

    /**
     * 确认收货
     */
    @PutMapping("/receipt/{orderId}")
    @Operation(summary = "根据订单号确认收货" , description = "根据订单号确认收货")
    public CommonResult<Object> receipt(@Valid @RequestBody OrderBaseReqDTO orderParam) {
        orderParam.setUserId(BigInteger.valueOf(getLoginUserId()));//测试写死用户id
        OrderDO order = orderService.getOrderByOrderId(orderParam.getOrderId());
        log.info("receipt: {}",order);
        if (!Objects.equals(order.getOrderStatus(), OrderStatusEnum.CONSIGNMENT.value())) {
            // 订单未发货，无法确认收货
            return CommonResult.error(ErrorCodeConstants.ORDER_NO_DELIVERY);
        }

        // 创建分账任务  TODO 分布式事务
        CreateDivideReqDTO reqDTO = new CreateDivideReqDTO(order.getOutTradeNo());
        payOrderApi.createDivide(reqDTO).getCheckedData();

        // 确认收货
        OrderDO orderDO=new OrderDO();
        orderDO.setId(orderParam.getOrderId());
        orderDO.setOrderStatus(OrderStatusEnum.SUCCESS.value());
        orderDO.setFinallyTime(LocalDateTime.now());
        orderService.updateOrderStatus(orderDO);
        // 发送mq消息
        orderReceiptForHzhProducer.sendOrderReceiptMessage(order, getLoginUserId());
        return success(orderParam.getOrderId());
    }


}
